package com.walkline.screen;

import javax.microedition.amms.control.camera.FlashControl;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;

import localization.RedFlowerResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Backlight;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RealtimeClockListener;
import net.rim.device.api.system.SystemListener2;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.FullScreen;

import com.walkline.app.RedFlowerAppConfig;
import com.walkline.util.Functions;

public class FlashLightScreen extends FullScreen implements RealtimeClockListener, SystemListener2, RedFlowerResource
{
    private final String[] encodings = Functions.getVideoEncodings();
    private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);
    private boolean _isFullScreen = false;

    private Player _player;
    private VideoControl _videoControl;
	private FlashControl _flashControl;

	private int backlightTimeout = Backlight.getTimeoutDefault();
	private int backlightCounter = 0;

	public FlashLightScreen()
	{
		if (!DeviceInfo.hasCamera())
		{
			Dialog.alert(getResString(MESSAGE_ERROR_NO_CAMERA));

			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {onClose();}
			});
		}

		if ((DeviceInfo.getBatteryStatus() & DeviceInfo.BSTAT_NO_CAMERA_FLASH) == DeviceInfo.BSTAT_NO_CAMERA_FLASH)
		{
			Dialog.alert(getResString(MESSAGE_ERROR_LOW_POWER));

			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {onClose();}
			});
		}

		setBackground(RedFlowerAppConfig.bg_Transparent);

        if (encodings != null && encodings.length > 0)
        {            
            if (encodings == null)
            {
                throw new NullPointerException("Video encoding can not be null");
            }        
        } else {
        	UiApplication.getUiApplication().invokeLater(new Runnable()
        	{
        		public void run() {Dialog.alert("This device is not capable of recording video");}
        	}); 
        }      

        try
        {
        	//_player =javax.microedition.media.Manager.createPlayer((this.getClass()).getResourceAsStream("/light.png"), "encoding=png&width=1&height=1");
        	_player =javax.microedition.media.Manager.createPlayer("capture://video?encoding=video/3gpp&mode=standard"); //+ encodings[0]); 
        	//_player =javax.microedition.media.Manager.createPlayer("capture://video?encoding=png&width=10&height=10");//video/3gpp&width=1&height=1&video_codec=MPEG-4&audio_codec=AMR");
        	_player.realize();
        	
        	_videoControl = (VideoControl) _player.getControl("VideoControl");
        	_flashControl = (FlashControl) _player.getControl("javax.microedition.amms.control.camera.FlashControl");
        }catch( final Exception e )
        {
           	if ( _player != null ) {_player.close();}
        	_player = null;
        }

        try
        {
        	final Field videoField = (Field) _videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
        	_videoControl.setDisplaySize(1, 1);
        	_videoControl.setVisible(true);
        	_player.start();

        	//VideoFieldManager vfm=new VideoFieldManager();
        	//vfm.add(videoField);
			//add(vfm);
        	add(videoField);
		} catch (final Exception e)
		{
			if (_player != null) {_player.close();}
        	_player = null;
		}
        
    	int newMode;
        switch (_flashControl.getMode())
        {
        	case FlashControl.OFF:
               newMode = FlashControl.FORCE;
               break;
            default:
                newMode = FlashControl.OFF;
                break;
        }

    	_flashControl.setMode(newMode);
    	Backlight.enable(true, 130);

    	Application.getApplication().addSystemListener(this);
    	Application.getApplication().addRealtimeClockListener(this);
    	add(new BitmapField(Bitmap.getBitmapResource("light.png"), LabelField.HCENTER | LabelField.VCENTER));
	}

	private String getResString(int key) {return _resources.getString(key);}

	protected boolean keyChar(char character, int status, int time)
	{
		switch (character)
		{
			case Characters.ESCAPE:
				onClose();
				return true;
			case Characters.SPACE:
				_isFullScreen = !_isFullScreen;

				if (_isFullScreen)
				{
					try {
						_videoControl.setDisplayFullScreen(true);
					} catch (MediaException e) {}
				} else {
					try {
						_videoControl.setDisplayFullScreen(false);
						_videoControl.setDisplaySize(1, 1);
					} catch (MediaException e) {}
				}
	            //_videoControl.setVisible(_isFullScreen);
				//_flashControl.setMode(_isVisable ? FlashControl.FORCE : FlashControl.OFF);
				return true;
		}

		return true;
	}

	protected boolean navigationClick( int status, int time ) 
    {
		onClose();
        return true;    
    }

	protected boolean trackwheelClick( int status, int time )
    {        
		onClose();    
        return true;
    }

	protected boolean touchEvent(TouchEvent message)
	{
		if (message.getEvent() == TouchEvent.UNCLICK)
		{
			onClose();
			return true;
		}

		return super.touchEvent(message);
	}

    public boolean onClose()
    {
    	if (_player != null)
    	{
    		_player.close();
    		_player = null;
    	}

    	Backlight.setTimeout(backlightTimeout);
    	Application.getApplication().removeSystemListener(this);
    	Application.getApplication().removeRealtimeClockListener(this);
    	UiApplication.getUiApplication().popScreen(this);
    	return true;
	}

	public void batteryGood() {}
	public void batteryLow() {}
	public void batteryStatusChange(int status) {}
	public void powerOff() {}
	public void powerUp() {}

	public void backlightStateChange(boolean on) {if (!on) {Backlight.enable(true, 130);}}

	public void cradleMismatch(boolean mismatch) {}
	public void fastReset() {}
	public void powerOffRequested(int reason) {}
	public void usbConnectionStateChange(int state) {}

	public void clockUpdated()
	{
		backlightCounter += 1;

		if (backlightCounter >= 2)
		{
			backlightCounter = 0;
			Backlight.enable(true, 130);
		}
	}
}